<template>
  <CommonPage title="操作员管理" content-row>
    <div class="w-72 pr-4">
      <a-tabs v-model:activeKey="activeDeptType" type="card" size="small">
        <a-tab-pane :key="DeptType.company" tab="公司架构">
          <a-skeleton v-if="tabSettingObj[DeptType.company].loading" active loading :avatar="false"></a-skeleton>
          <a-tree
            v-else-if="tabSettingObj[DeptType.company].data.length > 0"
            v-model:selectedKeys="selectedKeys"
            :tree-data="tabSettingObj[DeptType.company].data"
            :field-names="{ title: 'name', key: 'id' }"
            block-node
            show-line
            show-icon
            default-expand-all
          >
          </a-tree>
          <SlEmpty v-else />
        </a-tab-pane>
        <a-tab-pane :key="DeptType.cooperation" tab="合作框架">
          <a-skeleton v-if="tabSettingObj[DeptType.cooperation].loading" active loading :avatar="false"></a-skeleton>
          <a-tree
            v-else-if="tabSettingObj[DeptType.cooperation].data.length > 0"
            v-model:selectedKeys="selectedKeys"
            :tree-data="tabSettingObj[DeptType.cooperation].data"
            :field-names="{ title: 'name', key: 'id' }"
            block-node
            show-line
            show-icon
            default-expand-all
          >
          </a-tree>
          <SlEmpty v-else />
        </a-tab-pane>
      </a-tabs>
    </div>
    <div class="flex-1 flex flex-col overflow-hidden">
      <div class="mb-4">
        <a-button type="primary" :disabled="selectedKeys.length === 0" @click="showCreateModal">新增操作员</a-button>
      </div>
      <div class="flex-1 overflow-hidden">
        <SlTable
          class="table-pg-px0"
          :columns="columns"
          row-key="id"
          :data-source="tableData"
          :pagination="pagination"
          :loading="tableLoading"
        >
          <template #bodyCell="{ column, record }: BodyCellOptions<Partial<UserItem>>">
            <div v-if="column.key === 'oper'">
              <div class="mb-1">
                <a @click="showUpdateModal(record)">编辑</a>
                <a class="ml-2 text-red-400" @click="handleDelete(record)">删除</a>
              </div>
              <div>
                <a @click="showPwdModal(record)">修改密码</a>
                <!-- <a class="ml-2" @click="handleDelete(record)">权限管理</a> -->
              </div>
            </div>
            <div v-else-if="column.dataIndex === 'status'">
              <a-switch
                :checked="record.status === CommonStatus.enable"
                @change="handleStatusChange(record)"
              ></a-switch>
            </div>
            <div v-else-if="column.dataIndex === 'avatar'">
              <a-image :fallback="DEFAULT_IMG_BASE64_STR" :src="record.avatar" :width="48" />
            </div>
          </template>
        </SlTable>
      </div>
    </div>
    <CURDDialog
      ref="CURDModalIns"
      id-key="id"
      create-title="新增操作员"
      update-title="编辑操作员"
      delete-message="确认删除该操作员吗？"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :table-data="tableData"
      :curd="curd"
      :reload-table="reloadTable"
      :get-detail="getDetail"
      @open="handleOpen"
      @before-ok="beforeOk"
    />
    <UpdatePwdModal v-model:visible="updatePwdVisible" :user-id="curPwdUserId" />
  </CommonPage>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useCURD } from "/@/hooks/useCURD";
import { TableProps, message } from "ant-design-vue";
import {
  Api,
  changeUserStatus,
  getDataGroupList,
  getDeptList,
  getRoleOptions,
  getUserDetail,
} from "/@/api/main/system";
import { DeptItem, DeptType, UserItem } from "/@/api/main/system/models";
import { DEFAULT_IMG_BASE64_STR } from "/@/utils/file";
import {
  CURDAction,
  FormItemComponentType,
  FormItemData,
  ShowCURDModalOptions,
  CURDDialogExpose,
  CURDModalEvent,
} from "/@/components/CURDDialog/models";
import { CommonStatus } from "/@/api/models";
import { PatternKey } from "/@/utils/verify";
import { BodyCellOptions } from "/@/types/antd";
import InfoModal from "/@/components/InfoModal";
/**
 * 组织架构tab和tree
 */
interface TabSetting {
  loading: boolean;
  data: DeptItem[];
}
const tabSettingObj = ref<Record<DeptType, TabSetting>>({
  [DeptType.company]: {
    loading: false,
    data: [],
  },
  [DeptType.cooperation]: {
    loading: false,
    data: [],
  },
});
const activeDeptType = ref<DeptType>(DeptType.company);
watch(
  activeDeptType,
  async (deptType) => {
    const target = tabSettingObj.value[deptType];
    if (target.data.length === 0) {
      target.loading = true;
      const data = await getDeptList({ type: deptType });
      target.loading = false;
      if (data) {
        target.data = data;
      }
    }
    if (target.data.length > 0) {
      selectedKeys.value = [target.data[0].id];
    }
  },
  {
    immediate: true,
  }
);
const selectedKeys = ref<number[]>([]);
watch(selectedKeys, async (keys) => {
  reloadTable({
    model: {
      deptId: keys[0],
    },
  });
});
/**
 * 操作员表格
 */
const columns = ref<TableProps<UserItem>["columns"]>([
  {
    title: "账号",
    dataIndex: "username",
  },
  {
    title: "用户名称",
    dataIndex: "nickname",
  },
  {
    title: "头像",
    dataIndex: "avatar",
  },
  {
    title: "隶属架构",
    dataIndex: "deptName",
  },
  {
    title: "操作权限组",
    dataIndex: "roleNames",
  },
  {
    title: "手机",
    dataIndex: "mobile",
  },
  {
    title: "邮箱",
    dataIndex: "email",
  },
  {
    title: "状态",
    dataIndex: "status",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
  },
  // {
  //   title: "数据权限组",
  //   dataIndex: "dataPermisson",
  // },
  {
    title: "操作",
    key: "oper",
    width: 100,
  },
]);

const { pagination, tableData, tableLoading, curd, reloadTable } = useCURD<UserItem>({
  getPageUrl: Api.usersPage,
  cudUrl: Api.users,
});
/**
 * 操作员弹窗
 */
const CURDModalIns = ref<CURDDialogExpose>();
const showOptions = ref<ShowCURDModalOptions>();
const model = ref<Partial<UserItem>>({
  username: "",
  nickname: "",
  avatar: "",
  deptId: -1,
  roleIds: [],
  dataGroupIds: [],
  gender: 1,
  mobile: "",
  email: "",
});
const modelFormSetting = ref<FormItemData<Partial<UserItem>>[]>([
  {
    key: "username",
    labelDes: "默认密码123456",
    label: "登录账号",
    required: true,
  },
  {
    key: "nickname",
    label: "名称",
    required: true,
  },
  {
    key: "avatar",
    label: "头像",
    type: FormItemComponentType.IMGUPLOAD,
  },
  {
    key: "deptId",
    label: "部门",
    type: FormItemComponentType.TREESELECT,
    required: true,
    props: {
      fieldNames: { label: "name", value: "id" },
      treeData: [],
      disabled: true,
    },
    async getData() {
      const target = tabSettingObj.value[activeDeptType.value];
      return target.data;
    },
  },
  {
    key: "roleIds",
    label: "操作权限组",
    type: FormItemComponentType.SELECT,
    required: true,
    props: {
      placeholder: "请选择操作权限组",
      mode: "multiple",
    },
    async getData(e) {
      const data = await getRoleOptions();
      return data || [];
    },
  },
  {
    key: "dataGroupIds",
    label: "数据权限组",
    type: FormItemComponentType.SELECT,
    required: true,
    props: {
      placeholder: "请选择数据权限组",
      mode: "multiple",
    },
    async getData(e) {
      const data = await getDataGroupList();
      if (data) {
        return data.map((el) => ({
          value: el.id,
          label: el.name,
        }));
      }
      return [];
    },
  },
  {
    key: "gender",
    type: FormItemComponentType.SELECT,
    label: "性别",
    props: {
      options: [
        { value: 1, label: "男" },
        { value: 2, label: "女" },
      ],
    },
  },
  {
    key: "mobile",
    pattern: PatternKey.cellphone,
    label: "手机号",
  },
  {
    key: "email",
    label: "邮箱",
    pattern: PatternKey.email,
  },
]);
function handleOpen() {
  model.value.deptId = selectedKeys.value[0];
  if (CURDModalIns.value) {
    CURDModalIns.value.reloadFormItemComponentData("deptId");
  }
}
function beforeOk() {}
function showCreateModal() {
  showOptions.value = { action: CURDAction.CREATE };
}
function showUpdateModal(record) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function handleDelete(record) {
  showOptions.value = { action: CURDAction.DELETE, ids: [record.id] };
}
async function getDetail(record) {
  const data = await getUserDetail(record.id);
  return data || {};
}
/**
 * 修改密码
 */
const updatePwdVisible = ref(false);
const curPwdUserId = ref<number>();
function showPwdModal(record) {
  curPwdUserId.value = record.id;
  updatePwdVisible.value = true;
}
/**
 *
 */
function handleStatusChange(record: Partial<UserItem>) {
  InfoModal.warningConfirm({
    title: "提示",
    content: `确认${record.status === CommonStatus.enable ? "禁用" : "启用"}该用户吗？`,
    async onOk() {
      const re = await changeUserStatus(
        record.id as number,
        record.status === CommonStatus.enable ? CommonStatus.disable : CommonStatus.enable
      );
      if (re === undefined) {
        message.success("操作成功");
        reloadTable();
      }
    },
  });
}
</script>
